import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import cache from '@/utils/cache';
import login from '@/router/login/login';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { firstMenu } from '@/utils/map-route';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/view/main/main.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('@/view/error/404.vue')
  }
];

routes.push(login);

const router = createRouter({
  routes,
  history: createWebHistory()
});

// if (window.nextLoading === undefined) NextLoading.start();

router.beforeEach((to) => {
  NProgress.configure({ showSpinner: false });
  NProgress.start();
  if (to.path !== '/login') {
    const token = cache.getCache('token');
    if (!token) {
      return '/login';
    }
  }

  if (to.path == '/main') {
    return firstMenu.path;
  }
});

router.afterEach(() => {
  // NextLoading.done();
  NProgress.done();
});

export default router;
